package internal

import (
	"github.com/BurntSushi/toml"
	"lol.com/feb214-game/nest.git/log"
	"lol.com/feb214-game/nest.git/tools/fs"
	"talent.com/cube/conf/g"
)

//百人场房间配置
//下面的Limit是以元为单位的
type RoomConf struct {
	ID          int32
	Multi       int64
	BetLimit    int64
	BankerLimit int64
	See         bool
	Chips       []int64
	ChoiceChips []int64
	chipSet     map[int64]bool
}

type allRoomConf struct {
	Jmg *roomConfWrapper
}

type roomConfWrapper struct {
	Room []*RoomConf
}

type CmnConfigParser struct {
	fs.ParserMixIn
	config map[int32][]*RoomConf
	Init   bool
}

func (rcp *CmnConfigParser) ReloadConfig(path string, init bool) bool {
	modified, lastTs := rcp.CheckModify(path)
	if !modified {
		return false
	}
	var ar allRoomConf
	if _, err := toml.DecodeFile(path, &ar); err != nil {
		if init {
			panic(err)
		} else {
			log.Error("fail to reload %v for %v", path, err)
			return false
		}
	}
	nc := make(map[int32][]*RoomConf, 5)
	nc[g.Jmg] = ar.Jmg.Room
	rcp.Lock()
	rcp.config = nc
	rcp.SetLastModifyTime(path, lastTs)
	rcp.Unlock()
	return true
}

func (rcp *CmnConfigParser) ReloadCallback(value string) error {

	var ar allRoomConf
	if _, err := toml.Decode(value, &ar); err != nil {
		if rcp.Init {
			panic(err)
		} else {
			log.Error("fail to reload %v for %v", value, err)
			return err
		}
	}
	nc := make(map[int32][]*RoomConf, 5)
	nc[g.Jmg] = ar.Jmg.Room
	rcp.Lock()
	rcp.config = nc
	rcp.Init = false
	rcp.Unlock()
	return nil
}

func (rcp *CmnConfigParser) GetConfig() interface{} {
	rcp.RLock()
	defer rcp.RUnlock()
	return rcp.config
}

func (rc *RoomConf) IsValidChip(chip int64) bool {
	if len(rc.chipSet) == 0 {
		rc.chipSet = make(map[int64]bool, len(rc.Chips))
		for _, amount := range rc.Chips {
			rc.chipSet[amount] = true
		}
	}
	return rc.chipSet[chip]
}
